package org.example.httphandler;

import com.sun.net.httpserver.HttpExchange;
import org.example.utils.FileRead;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

/**
 * @author 胡帅博
 * @date 2021/6/11 14:09
 */
public class ResourceHandler extends DefaultHandler{

    byte[] workServiceJsBytes;
    byte[] installJsBytes;
    volatile boolean loaded = false;

    @Override
    public void handle(HttpExchange t) throws IOException {

        super.handle(t);
        if (!loaded) {
            loadResources();
        }
        URI requestURI = t.getRequestURI();

        String path = requestURI.getPath();

        if ("/install.js".equals(path)) {
            t.getResponseHeaders().set("content-type", "application/javascript; charset=utf-8");
            t.sendResponseHeaders(200, installJsBytes.length);
            OutputStream os = t.getResponseBody();
            os.write(installJsBytes);
            os.close();
        } else if ("/service-worker.js".equals(path)) {

            t.getResponseHeaders().set("content-type", "application/javascript; charset=utf-8");

            t.sendResponseHeaders(200, workServiceJsBytes.length);
            OutputStream os = t.getResponseBody();
            os.write(workServiceJsBytes);
            os.close();

        } else {
            t.sendResponseHeaders(404, 0);
            t.close();
        }


    }


    private synchronized void loadResources() {
        if (!loaded) {
            try {
                byte[] bytes = FileRead.readFromJar("/install.js");
                installJsBytes = bytes;

                workServiceJsBytes = FileRead.readFromJar("/service-worker.js");


                loaded = true;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
